package com.banfan.almond.web.controller;


import com.banfan.almond.entity.entity.Blog;
import com.banfan.almond.entity.vo.BlogVO;
import com.banfan.almond.utils.ResultUtil;
import com.banfan.almond.web.annotation.AvoidRepeatableCommit.AvoidRepeatableCommit;
import com.banfan.almond.web.security.SecurityUser;
import com.banfan.almond.web.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/blog")
public class BlogController {

    @Autowired
    private BlogService blogService;


    @GetMapping("/hot")
    public String getHotBlog() {
        return blogService.getHotBlog();
    }

    @GetMapping("/user/{currentPage}")
    public String getUserBlog(@PathVariable Integer currentPage, Authentication authentication) {
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        return blogService.getUserBlog(securityUser.getUserUid(),currentPage);
    }

    @GetMapping("/userBlogCount")
    public String getUserBlogCount(Authentication authentication) {
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        return blogService.getUserBlogCount(securityUser.getUserUid());
    }

    @GetMapping("/{uid}")
    public String get(@PathVariable Integer uid,  Authentication authentication) {
        Blog blog = blogService.getById(uid);
        //to 没有的id
        return ResultUtil.successWithData(blog);
    }

    @AvoidRepeatableCommit(timeout = 1000)
    @PostMapping("/")
    public String post(@RequestBody BlogVO blogVO,  Authentication authentication) {
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        blogVO.setUserUid(securityUser.getUserUid());
        return blogService.addBlog(blogVO);
    }


    @DeleteMapping("/{uid}")
    public String delete(@PathVariable Integer uid,  Authentication authentication) {
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        // 参数校验
//        ThrowableUtils.checkParamArgument(result);
        return blogService.deleteBlog(securityUser.getUserUid(),uid);
    }

}

